import env from '@/core/plugins/env'
const baseUrl = env.getConfig().baseUrl
/**
 * 发送请求
 *
 * @param method 请求方式
 * @param url 请求地址
 * @param data 请求参数
 * @param config 请求配置
 * @returns {Promise<unknown>}
 */
const request = (method, url, data, config = {}) => {
	return new Promise((resolve, reject) => {
		const headers = config.headers || {}
		uni.request({
			url: baseUrl + url,
			data: data,
			method: method,
			header: {
				'Content-Type': 'application/json',
				// 携带认证token
				'walle-auth-token': uni.getStorageSync('walle-auth-token') || '',
				...headers
			},
			// 请求成功
			success: (res) => {
				if (!res.data.success) {
					return reject(res.data)
				}
				resolve(res.data.data)
			},
			// 请求失败
			fail: (err) => {
				reject(new Error(err))
			},
			// 请求完成
			complete: () => {
				uni.stopPullDownRefresh()
				uni.hideLoading()
			}
		})
	})
}

export default {
	get (url, data, config) {
		return request('GET', url, data, config)
	},
	post (url, data, config) {
		return request('POST', url, data, config)
	},
	put (url, data, config) {
		return request('PUT', url, data, config)
	},
	delete (url, data, config) {
		return request('DELETE', url, data, config)
	}
}
